
#include "task.h"
#include "kernel.h"

extern void switch_task();

extern task_t* task_table[NR_TASKS];

task_t *current = NULL;

task_t* find_ready_task()
{
    for (int i = 0; i < NR_TASKS; i++)
    {
        task_t *task = task_table[i];
        if (NULL == task)
        {
            continue;
        }
        if (task_table[i]->state == TASK_READY)
        {
            return task_table[i];
        }
    }
    return NULL;
}

void sched()
{
    if (NULL != current)
    {
        if (TASK_SLEEPING != current->state)
        {
            current->state = TASK_READY;
        }
        current = NULL;
    }

    task_t *task = find_ready_task();
    if (NULL == task)
    {
        // printk("no ready task\n");
        return;
    }
    task->state = TASK_RUNNING;
    current = task;
    switch_task();
}

task_t* sched64()
{
    if (NULL != current)
    {
        if (TASK_SLEEPING != current->state)
        {
            current->state = TASK_READY;
        }

    }

    task_t* next = find_ready_task();
    if (NULL == next)
    {
        return NULL;
    }
    next->state = TASK_RUNNING;
    return next;

}